package design_patterns.command;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by nuno-rafael-figueiredo on 12-07-2014.
 */
public class CommandQueue2<T> extends Command{
    private final List<T> queue;
    private CommandFactory<T> factory;

    public CommandQueue2(T[] args, CommandFactory<T> factory) {
        this.queue = new ArrayList<>(Arrays.asList(args));
        this.factory = factory;
    }

    @Override
    public void execute() {
        next();
    }

    private void next() {
        if (queue.isEmpty()){
            finish();
            return;
        }

        Command command = factory.create(queue.remove(0));

        command.onFinish((a, b, c) -> next());
        command.execute();
    }

    public interface CommandFactory<T>{
        Command create(T item);
    }
}
